﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Controls.Primitives; // 添加这行
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CPlatePrintSys.Win.Views
{
    public static class VisualTreeHelperExtensions
    {
        // 查找可视化父元素
        public static T FindVisualParent<T>(this DependencyObject child) where T : DependencyObject
        {
            // 获取父元素
            var parentObject = VisualTreeHelper.GetParent(child);

            // 已经到达根节点
            if (parentObject == null)
                return null;

            // 检查父元素是否是我们要找的类型
            if (parentObject is T parent)
                return parent;

            // 递归继续向上查找
            return FindVisualParent<T>(parentObject);
        }
        // 支持名称查找的扩展方法
        public static T FindVisualChild<T>(this DependencyObject parent, string childName)
            where T : DependencyObject
        {
            if (parent == null) return null;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child != null && child is T)
                {
                    if (child is FrameworkElement frameworkElement &&
                        frameworkElement.Name == childName)
                    {
                        return (T)child;
                    }
                }

                var result = FindVisualChild<T>(child, childName);
                if (result != null)
                    return result;
            }
            return null;
        }

        // 原始的不带名称参数的版本
        public static T FindVisualChild<T>(this DependencyObject obj) where T : DependencyObject
        {
            if (obj == null) return null;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is T)
                    return (T)child;

                var childOfChild = FindVisualChild<T>(child);
                if (childOfChild != null)
                    return childOfChild;
            }
            return null;
        }
    }
    /// <summary>
    /// MaterialManageView.xaml 的交互逻辑
    /// </summary>
    public partial class MaterialManageView : UserControl
    {
        public MaterialManageView()
        {
            InitializeComponent();
        }

        private ScrollViewer _dataGridScrollViewer;
        public void DataGrid_Loaded(object sender, RoutedEventArgs e)
        {
            _dataGridScrollViewer = FindVisualChild<ScrollViewer>(scrollableGrid);
            if (_dataGridScrollViewer != null)
            {
                _dataGridScrollViewer.ScrollChanged += DataGrid_ScrollChanged;
            }
        }

        public void DataGrid_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (e.HorizontalChange != 0)
            {
                FixLastColumn();
            }
        }




        private void FixLastColumn()
        {
            if (_dataGridScrollViewer == null) return;

            double scrollX = _dataGridScrollViewer.HorizontalOffset;
            int lastColIndex = scrollableGrid.Columns.Count - 1;

            // 1. Fix HEADER
            var columnHeader = GetColumnHeader(scrollableGrid, lastColIndex);
            if (columnHeader != null)
            {
                var headerPanel = columnHeader.FindVisualChild<StackPanel>("fixedHeaderPanel");
                if (headerPanel != null)
                {
                    headerPanel.RenderTransform = new TranslateTransform
                    {
                        X = _dataGridScrollViewer.HorizontalOffset - 753
                    };
                }
            }

            // 2. Fix CELLS
            foreach (var item in scrollableGrid.Items)
            {
                var row = scrollableGrid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                var cell = GetCell(scrollableGrid, row, lastColIndex);
                if (cell != null)
                {
                    cell.RenderTransform = new TranslateTransform
                    {
                        X = _dataGridScrollViewer.HorizontalOffset - 773
                    };
                    Panel.SetZIndex(cell, 10);
                }
            }

            // 3. Buttons panel (already handled in your code)
            UpdateFixedColumnPosition();
        }

        private void UpdateFixedColumnPosition()
        {
            if (_dataGridScrollViewer == null) return;

            // 1. Get the first column's position (relative to DataGrid)
            Point firstColumnPosition = GetFirstColumnPosition();

            // 2. Calculate available space for the last column
            double scrollableWidth = _dataGridScrollViewer.ViewportWidth;
            double lastColumnWidth = 230; // Match your last column's width

            // 3. Compute the required X-offset to fix the last column
            double fixedX = firstColumnPosition.X + scrollableWidth - lastColumnWidth;

            // 4. Apply the transform to the last column
            int lastColumnIndex = scrollableGrid.Columns.Count - 1;

            foreach (var item in scrollableGrid.Items)
            {
                var row = scrollableGrid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                if (row == null) continue;

                var lastCell = GetCell(scrollableGrid, row, lastColumnIndex);
                if (lastCell != null)
                {
                    lastCell.RenderTransform = new TranslateTransform
                    {
                        X = _dataGridScrollViewer.HorizontalOffset - 833
                    };
                    Panel.SetZIndex(lastCell, 10); // Ensure it stays on top
                }
            }
        }

        // Helper to get column header
        private DataGridColumnHeader GetColumnHeader(DataGrid grid, int columnIndex)
        {
            var headersPresenter = FindVisualChild<DataGridColumnHeadersPresenter>(grid);
            return headersPresenter?.ItemContainerGenerator.ContainerFromIndex(columnIndex)
                   as DataGridColumnHeader;
        }

        // Helper method to get the position of the first column
        private Point GetFirstColumnPosition()
        {
            if (scrollableGrid.Items.Count == 0)
                return new Point(0, 0);

            // Get the first row
            var firstRow = scrollableGrid.ItemContainerGenerator
                .ContainerFromIndex(0) as DataGridRow;
            if (firstRow == null) return new Point(0, 0);

            // Get the first cell (column 0)
            var firstCell = GetCell(scrollableGrid, firstRow, 0);
            if (firstCell == null) return new Point(0, 0);

            // Get position relative to the DataGrid
            return firstCell.TranslatePoint(new Point(0, 0), scrollableGrid);
        }

        // Helper to find ScrollViewer
        private ScrollViewer GetScrollViewer(DependencyObject parent)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child is ScrollViewer sv) return sv;
                var result = GetScrollViewer(child);
                if (result != null) return result;
            }
            return null;
        }
        // Helper methods
        private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is T)
                    return (T)child;
                var childOfChild = FindVisualChild<T>(child);
                if (childOfChild != null)
                    return childOfChild;
            }
            return null;
        }

        private DataGridCell GetCell(DataGrid grid, DataGridRow row, int column)
        {
            if (row == null) return null;
            var presenter = FindVisualChild<DataGridCellsPresenter>(row);
            if (presenter == null) return null;

            var cell = presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
            if (cell == null)
            {
                grid.ScrollIntoView(row, grid.Columns[column]);
                cell = presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
            }
            return cell;
        }
        // 按钮点击事件处理
        private void Edit_Click(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender;
            var row = button.FindVisualParent<DataGridRow>();
            if (row != null)
            {
                var selectedItem = row.Item;
                // 处理编辑逻辑...
            }
        }


        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender;
            var item = button.DataContext; // This is your bound data item
                                           // Handle delete...
        }

        private static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
        {
            while (child != null && !(child is T))
            {
                child = VisualTreeHelper.GetParent(child);
            }
            return child as T;
        }
    }
}
